#include "pagecalculationservice.h"
#include "layoutstatemanager.h"
#include "systemconfig.h"
#include <QDebug>
#include <QtMath>
PageCalculationService::PageCalculationService(QObject* parent)
    : QObject(parent)
{
}
// === 显示页数计算 ===
int PageCalculationService::calculateDisplayPages(const UnifiedFileInfo& fileInfo) const
{
    if (fileInfo.fileIdentity.isEmpty()) {
        return 1;
    }
    int basePageCount = calculateBasePageCount(fileInfo);
    LayoutMode layoutMode = getLayoutMode(fileInfo);
    int displayPages = basePageCount;
    // 根据布局模式调整显示页数
    switch (layoutMode) {
    case LayoutMode::SingleColumn:
        // 单栏模式：基础页数
        displayPages = basePageCount;
        break;
    case LayoutMode::TwoColumns:
        // 双栏模式：每页显示2个基础页面
        displayPages = qCeil(static_cast<double>(basePageCount) / 2.0);
        break;
    case LayoutMode::ThreeColumns:
        // 三栏模式：每页显示3个基础页面
        displayPages = qCeil(static_cast<double>(basePageCount) / 3.0);
        break;
    default:
        displayPages = basePageCount;
        break;
    }
    return qMax(1, displayPages); // 至少显示1页
}
QMap<QString, int> PageCalculationService::calculateDisplayPages(const QList<UnifiedFileInfo>& files) const
{
    QMap<QString, int> displayPagesMap;
    for (const UnifiedFileInfo& fileInfo : files) {
        int displayPages = calculateDisplayPages(fileInfo);
        displayPagesMap[fileInfo.fileIdentity] = displayPages;
    }
    return displayPagesMap;
}
// === 全局页码映射计算 ===
QMap<QString, int> PageCalculationService::calculateGlobalPageMapping(const QList<UnifiedFileInfo>& orderedFiles) const
{
    QMap<QString, int> globalMapping;
    int currentPage = 1;
    for (int i = 0; i < orderedFiles.size(); ++i) {
        const UnifiedFileInfo& fileInfo = orderedFiles[i];
        int displayPages = calculateDisplayPages(fileInfo);
        globalMapping[fileInfo.fileIdentity] = currentPage;
        currentPage += displayPages;
    }
    return globalMapping;
}
QPair<int, int> PageCalculationService::calculateFileGlobalRange(const UnifiedFileInfo& fileInfo,
                                                               const QList<UnifiedFileInfo>& filesInOrder) const
{
    // 首先计算全局页码映射
    QMap<QString, int> globalMapping = calculateGlobalPageMapping(filesInOrder);
    if (!globalMapping.contains(fileInfo.fileIdentity)) {
        return {0, 0};
    }
    int startPage = globalMapping[fileInfo.fileIdentity];
    int displayPages = calculateDisplayPages(fileInfo);
    int endPage = startPage + displayPages - 1;
    return {startPage, endPage};
}
// === 页码转换 ===
int PageCalculationService::convertToGlobalPage(const QString& fileIdentity, int localPage,
                                               const QMap<QString, int>& globalMapping) const
{
    if (!globalMapping.contains(fileIdentity)) {
        return 0;
    }
    if (localPage < 0) {
        return 0;
    }
    int startPage = globalMapping[fileIdentity];
    int globalPage = startPage + localPage;
    return globalPage;
}
int PageCalculationService::convertToLocalPage(int globalPage, const QString& fileIdentity,
                                              const QList<UnifiedFileInfo>& filesInOrder) const
{
    if (globalPage < 1) {
        return -1;
    }
    // 计算文件的全局页码范围
    QPair<int, int> fileRange = calculateFileGlobalRange(
        [&]() -> UnifiedFileInfo {
            for (const UnifiedFileInfo& info : filesInOrder) {
                if (info.fileIdentity == fileIdentity) {
                    return info;
                }
            }
            return UnifiedFileInfo();
        }(),
        filesInOrder
    );
    int startPage = fileRange.first;
    int endPage = fileRange.second;
    if (globalPage < startPage || globalPage > endPage) {
        return -1;
    }
    int localPage = globalPage - startPage;
    return localPage;
}
// === 验证和调试 ===
QPair<bool, QString> PageCalculationService::validatePageMapping(const QList<UnifiedFileInfo>& filesInOrder,
                                                               const QMap<QString, int>& globalMapping) const
{
    QStringList errors;
    // 检查文件数量一致性
    if (filesInOrder.size() != globalMapping.size()) {
        errors.append(QString("文件数量不一致: 顺序列表 %1, 映射表 %2")
                     .arg(filesInOrder.size()).arg(globalMapping.size()));
    }
    // 检查每个文件的映射
    int calculatedTotal = 0;
    for (int i = 0; i < filesInOrder.size(); ++i) {
        const UnifiedFileInfo& fileInfo = filesInOrder[i];
        if (!globalMapping.contains(fileInfo.fileIdentity)) {
            errors.append(QString("文件 %1 不在映射表中").arg(fileInfo.fileName));
            continue;
        }
        int expectedStartPage = calculatedTotal + 1;
        int actualStartPage = globalMapping[fileInfo.fileIdentity];
        if (actualStartPage != expectedStartPage) {
            errors.append(QString("文件 %1 起始页码错误: 期望 %2, 实际 %3")
                         .arg(fileInfo.fileName).arg(expectedStartPage).arg(actualStartPage));
        }
        int displayPages = calculateDisplayPages(fileInfo);
        calculatedTotal += displayPages;
    }
    // 检查页码连续性
    QList<int> startPages = globalMapping.values();
    std::sort(startPages.begin(), startPages.end());
    for (int i = 1; i < startPages.size(); ++i) {
        int prevEnd = startPages[i-1] + calculateDisplayPages(
            [&]() -> UnifiedFileInfo {
                for (const UnifiedFileInfo& info : filesInOrder) {
                    if (globalMapping[info.fileIdentity] == startPages[i-1]) {
                        return info;
                    }
                }
                return UnifiedFileInfo();
            }()) - 1;
        if (startPages[i] != prevEnd + 1) {
            errors.append(QString("页码不连续: 文件起始页码 %1 与前一文件结束页码 %2 之间存在间隙")
                         .arg(startPages[i]).arg(prevEnd));
        }
    }
    bool isValid = errors.isEmpty();
    QString errorMessage = errors.isEmpty() ? "验证通过" : errors.join("; ");
    return {isValid, errorMessage};
}
QString PageCalculationService::generateDebugInfo(const QList<UnifiedFileInfo>& filesInOrder,
                                                 const QMap<QString, int>& globalMapping) const
{
    QString info;
    QTextStream stream(&info);
    stream << "=== PageCalculationService 调试信息 ===" << Qt::endl;
    stream << "文件总数: " << filesInOrder.size() << Qt::endl;
    stream << "映射表大小: " << globalMapping.size() << Qt::endl;
    stream << Qt::endl;
    stream << "文件顺序和页码映射:" << Qt::endl;
    for (int i = 0; i < filesInOrder.size(); ++i) {
        const UnifiedFileInfo& fileInfo = filesInOrder[i];
        int displayPages = calculateDisplayPages(fileInfo);
        int startPage = globalMapping.value(fileInfo.fileIdentity, 0);
        int endPage = startPage + displayPages - 1;
        stream << QString("  [%1] %2")
                  .arg(i, 2).arg(fileInfo.fileName.right(25))
                  .arg(startPage).arg(endPage).arg(displayPages)
    }
    stream << Qt::endl;
    stream << "页码映射表:" << Qt::endl;
    for (auto it = globalMapping.begin(); it != globalMapping.end(); ++it) {
        QString fileIdentity = it.key();
        int startPage = it.value();
        stream << QString("  %1: %2").arg(fileIdentity.right(20)).arg(startPage) << Qt::endl;
    }
    // 验证结果
    auto validationResult = validatePageMapping(filesInOrder, globalMapping);
    stream << Qt::endl;
    stream << "验证结果: " << (validationResult.first ? "通过" : "失败") << Qt::endl;
    if (!validationResult.second.isEmpty()) {
        stream << "验证信息: " << validationResult.second << Qt::endl;
    }
    return info;
}
// === 私有方法 ===
int PageCalculationService::calculateBasePageCount(const UnifiedFileInfo& fileInfo) const
{
    // 基础页数计算逻辑
    // 这里可以根据文件类型和内容进行更复杂的计算
    // 目前使用文件信息中存储的页数或默认值
    int basePageCount = 1;
    // 如果文件信息中有页面数量，使用它
    if (fileInfo.pageCount > 0) {
        basePageCount = fileInfo.pageCount;
    } else {
        // 否则根据文件类型估算
        if (fileInfo.fileName.toLower().endsWith(".pdf")) {
            // PDF文件可能需要特殊处理
            basePageCount = 10; // 默认估算值
        } else {
            // 图片文件通常只有一页
            basePageCount = 1;
        }
    }
    return basePageCount;
}
LayoutMode PageCalculationService::getLayoutMode(const UnifiedFileInfo& fileInfo) const
{
    // 使用LayoutStateManager获取布局模式
    SystemConfig config; // 创建默认配置
    return LayoutStateManager::getDefaultLayoutModeWithConfig(fileInfo.filePath, config, 0, 0);
}